#!/bin/sh

 # $2::1 = "$"
 
 i=1
 res=0
 op_k=0
 opt_f="-f"
 opt_k="-k"
 opt_c="-c"
 nb_param=$#

 if [ $1 ]; then
     while [ $i != $nb_param ]
     do
	 if [ $res = 0 ]; then
	     if [ $1 = "$opt_f" ]; then
		 if [ -e  "$2" ]; then
		     bd_name="$2"
		 else	     
		     echo "File $2 doesn't exist"
		     exit 4
		 fi
	     elif [ $1 = "$opt_k" ]; then
		 let "op_k = 1"
	     elif [ $1 = "$opt_c" ]; then
		 if [ -e "$2" ]; then
		     echo "File $2 already exist"
		     exit 3
		 else
		     bd_name="$2"
		 fi
	     elif [ $1 = "put" ]; then
		 if [ ! -e $bd_name ]; then
		     echo "" >> $bd_name
		 fi
		 sed -i "/$2/d" $bd_name
		 let "res = 1"
		 if [ $3 ]; then
		     echo "$2=$3" >> $bd_name
		 else
		     echo "$2" >> $bd_name
		 fi
	     elif [ $1 = "del" ]; then
		 let "res = 1"
		 if [ $3 ]; then
		     value=$(grep "$3" $bd_name | cut -d"=" -f2)
		     if [ $3 = $value ]; then
			 sed -i "/$2/d" $bd_name
		     fi
		 else
		     sed -i "/$2/d" $bd_name | cut -d"=" -f2
		 fi
	     elif [ $1 = "select" ]; then
		 let "res = 1"
		 if [ $op_k = 1 ]; then
		     grep "$2" $bd_name
		 else
		     grep "$2" $bd_name | cut -d"=" -f2
		 fi
	     fi
	 else
	     exit 2
	 fi
	 let "i = i + 1"
	 shift 1
     done
 else
     echo "USAGE : 
		bdsh.sh [-k] [-f <db_file>] (put (<clef> | $<clef>) (<valeur> | $<clef>) |
                del (<clef> | $<clef>) [<valeur> | $<clef>] | select [<expr> | $<clef>] )"
 fi